package com.jy.api.service.impl;

import com.jy.api.controller.admin.params.BillRuleReq;
import com.jy.api.dao.BillRuleDao;
import com.jy.api.dao.LeaseProductDao;
import com.jy.api.domain.BillRule;
import com.jy.api.domain.LeaseProduct;
import com.jy.api.domain.LeaseProductExtra;
import com.jy.api.service.BillRuleService;
import com.jy.api.util.Result;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by xiaohua on 2019/4/28.
 */
@Service
public class BillRuleServiceImpl implements BillRuleService {
    @Autowired
    private BillRuleDao billRuleDao;
    @Autowired
    private LeaseProductDao leaseProductDao;


    @Override
    public List<BillRule> findRuleList(String storeId) {
        return billRuleDao.findAllByStoreIdAndEnabled(storeId, true);
    }

    @Override
    public void deleteById(int id) {
        BillRule billRule = billRuleDao.findOne(id);

        if (null != billRule) {
            billRule.setEnabled(false);
        }
        billRuleDao.save(billRule);
    }

    @Override
    public Result updateOrSave(BillRuleReq req) {
        BillRule billRule;
        if (0 == req.getId()) {
            billRule = new BillRule();
            BeanUtils.copyProperties(req, billRule, "id", "enabled");
        } else {
            billRule = billRuleDao.findOne(req.getId());
            if (null != billRule) {
                BeanUtils.copyProperties(req, billRule, "id", "enabled");
            }
        }
        if (req.getId()>0){
            List<LeaseProduct> products = leaseProductDao.findByStoreIdOrderByQueueDesc(billRule.getStoreId());
            for (LeaseProduct product : products) {
                for (LeaseProductExtra extra : product.getExtras()) {
                    if (extra.getRuleId()==billRule.getId()){
                            extra.setRuleName(billRule.getName());
                            product.setUpdateTime(new Date());
                    }
                }
            }
            leaseProductDao.save(products);
        }
        billRuleDao.save(billRule);
        return new Result(200, "操作成功");
    }


}
